<template>
  <div class="line-chart">
    <h4>{{ title }}</h4>
    <div class="chart">
      <chart
        ref="chartRef"
        :option="refChartOption"
        :style="{ height: chartHeight }"
        @zrender:click="renderClickHandle"
        @selected:click="handleselected"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, PropType, watch, onMounted } from 'vue';
import { Chart } from '@/components';
import echarts from 'echarts';
import { pull } from 'lodash';
export interface TimelineItem {
  [key: string]: string | number;
}
import line1 from '@/assets/image/statistics/line1.svg';
import line2 from '@/assets/image/statistics/line2.svg';
import line3 from '@/assets/image/statistics/line3.svg';
import line4 from '@/assets/image/statistics/line4.svg';
export default defineComponent({
  props: {
    data: {
      type: Array as PropType<TimelineItem[]>,
      default: () => [],
    },
    title: {
      type: String,
      default: '',
    },
    fieldNames: {
      type: Object,
      default: () => ({
        name: 'name',
        values: ['value'],
      }),
    },
    height: {
      type: Number,
      default: 300,
    },
    legend: {
      type: Array,
      default: () => {
        return [];
      },
    },
    type: {
      type: String,
      default: '智能',
    },
  },
  setup(props, { emit }) {
    const chartRef = ref<any>();
    const colorArr = ref<any>('');
    const areaStyle = ref<any>({});
    const legend = computed(() => props.legend);
    const legenddata = computed(() => {
      let str = pull(props.legend, '同比增长率');
      let arr: any = [];
      str.forEach(item => {
        if (item == '去年同期') {
          arr.push({
            name: item,
            icon: setLine(),
            lineStyle: {
              type: 'dotted',
            },
          });
        } else {
          arr.push({
            name: item,
            icon: 'line',
          });
        }
      });
      return arr;
    });
    const chartOption = {
      //   color: ['#1790ff', '#12c2c2', '#ee6666'],
      color: colorArr,
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        left: 'right',
        itemWidth: 15,
        itemHeight: 2,
        data: legenddata,
      },
      grid: {
        left: '3%',
        right: '4%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [] as string[],
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          lineHeight: '25',
        },
      },
      yAxis: {
        type: 'value',
        axisTick: {
          show: false,
        },
        axisLine: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      dataZoom: {},
      series: [
        {
          name: legend.value[0],
          type: 'line',
          data: [] as number[],
          showSymbol: false,
        },
        {
          name: legend.value[1],
          type: 'line',
          smooth: false,
          data: [] as number[],
          showSymbol: false,
        },
      ] as Array<any>,
    };
    legend.value.forEach((e, i) => {
      if (e == '去年同期') {
        chartOption.series[i] = {
          name: e,
          type: 'line',
          data: [] as number[],
          smooth: false,
          itemStyle: {
            normal: {
              lineStyle: {
                type: 'dotted',
                width: '2',
              },
            },
          },
        };
      } else {
        chartOption.series[i] = {
          name: e,
          type: 'line',
          data: [] as number[],
          showSymbol: false,
          areaStyle: areaStyle.value,
        };
      }
    });

    const refChartOption = ref(chartOption);
    const chartHeight = computed(() => `${props.height}px`);

    const setChartOption = (data: any[]) => {
      const xAxis: string[] = [];
      interface SeriesDataMap {
        [key: string]: Array<any>;
      }
      const seriesDataMap: SeriesDataMap = {};
      data.forEach(item => {
        const name = item[props.fieldNames.name];
        props.fieldNames.values.forEach(value => {
          if (seriesDataMap[value]) {
            seriesDataMap[value].push(item[value]);
          } else {
            seriesDataMap[value] = [item[value]];
          }
        });
        xAxis.push(name);
      });
      refChartOption.value.xAxis.data = xAxis;
      Object.values(seriesDataMap).forEach((o, i) => {
        refChartOption.value.series[i].data = o;
      });
    };

    const renderClickHandle = e => {
      if (e?.topTarget?.type === 'Line') {
        const index = chartRef.value.getIndexByEvent(e);
        const item = props.data[index];
        emit('zrender:click', index, item);
      }
    };
    const line = ref<string>('');
    const setLine = () => {
      if (props.type == '智能') {
        line.value = `image://${line1}`;
        return `image://${line1}`;
      } else if (props.type == '传统') {
        line.value = `image://${line3}`;
        return `image://${line3}`;
      } else {
        line.value = `image://${line2}`;
        return `image://${line2}`;
      }
    };
    const handleselected = e => {
      if (!e.selected.去年同期) {
        chartOption.legend.data.value[1].icon = `image://${line4}`;
        setChartOption(props.data);
      } else {
        chartOption.legend.data.value[1].icon = line.value;
        setChartOption(props.data);
      }
    };
    watch(
      () => props.data,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.height,
      () => {
        setChartOption(props.data);
      },
    );
    watch(
      () => props.type,
      () => {
        colorArr.value =
          props.type == '智能' ? '#E99220' : props.type == '传统' ? '#3191FF' : '#1CCAFF';
        if (props.type == '智能') {
          areaStyle.value.normal = {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#E99220 ' },
              { offset: 1, color: '#25272D' },
            ]),
          };
        } else if (props.type == '传统') {
          areaStyle.value.normal = {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#3191FF ' },
              { offset: 1, color: '#25272D' },
            ]),
          };
        } else if (props.type == '接警') {
          areaStyle.value.normal = {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
              { offset: 0, color: '#1CCAFF ' },
              { offset: 1, color: '#25272D' },
            ]),
          };
        }
        setChartOption(props.data);
      },
      {
        immediate: true,
        deep: true,
      },
    );
    onMounted(() => {
      setChartOption(props.data);
    });
    return {
      areaStyle,
      chartHeight,
      refChartOption,
      renderClickHandle,
      chartRef,
      handleselected,
      line,
    };
  },
  components: {
    Chart,
  },
});
</script>

<style lang="less" scoped></style>
